package 第一步;
import java.util.*;
import java.util.Map.Entry;
import java.io.*;

public class function3 {
    public static void main(String[] args) throws FileNotFoundException
    {
        System.out.println("Press any letter to start word count:");
        Scanner s = new Scanner(System.in);
        if (s.nextLine() == null)
        {
            s.close();
            System.exit(0);
        } else
        {
            s.close();
        }
        Map<String,Integer> map=new TreeMap<String,Integer>();
        File file=new File("C:\\Users\\随\\Desktop\\ceshiji\\one.txt" + "");//将文本文件与代码放入同一目录下，所以只写了相对路径
        Reader reader=null;
        StringBuilder exist=new StringBuilder();
        try
        {
            reader=new InputStreamReader(new FileInputStream(file));
            int tmpchar;
            while((tmpchar=reader.read())!=-1)
            {
                if(isCharacter(tmpchar))
                {
                    exist.append((char)tmpchar);
                }
                else
                {
                    Addword(exist.toString(),map);
                    exist=new StringBuilder();
                }
            }
        }catch(IOException e)
        {
            e.printStackTrace();
        }
        List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(list,new Comparator<Map.Entry<String,Integer>>()
        {
            public int compare(Entry<String,Integer> o1,Entry<String,Integer> o2)
            {
                return (o2.getValue().compareTo(o1.getValue()));//降序排序
            }
        });
        int i=10;
        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()&&i>0)
        {
            String key=iter.next();
            System.out.println((String)key+":"+map.get(key));
            i--;
        }
    }
    public static void Addword(String str,Map<String,Integer> map)//是字母就append组成单词
    {
        str=str.toLowerCase();
        Integer count=map.get(str);
        if(count==null)
        {
            map.put(str,1);
        }
        else
        {
            map.put(str,count+1);
        }
    }
    public static boolean isCharacter(int tmpchar)//判断是否是字母
    {
        if(tmpchar>=65&&tmpchar<=90)
        {
            return true;
        }
        else if(tmpchar>=97&&tmpchar<=122)
        {
            return true;
        }
        return false;
    }
}